//
//  informationDetailVC.m
//  HappyStore
//
//  Created by 陈锋 on 16/6/1.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "informationDetailVC.h"
#import "projectCell.h"
#import "PinLunCell.h"
@interface informationDetailVC ()<UIWebViewDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>{
    NSInteger page;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (weak, nonatomic) IBOutlet UITextField *textfiled;
@property (weak, nonatomic) IBOutlet UIButton *zanBtn;
@property (weak, nonatomic) IBOutlet UIButton *guanZhuBtn;

@property (strong, nonatomic) UIWebView * webView;
@property (strong, nonatomic) UITableView * tableview;
// 数据源
@property (strong, nonatomic) NSDictionary * dataDict;
@property (strong, nonatomic) NSMutableArray * commentArr;
@end

@implementation informationDetailVC

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:YES];
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    page = 0;
    [self sendRequest];
}
-(void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 初始化
-(NSDictionary *)dataDict{
    if (!_dataDict) {
        _dataDict = [NSDictionary dictionary];
    }
    return _dataDict;
}

-(NSMutableArray *)commentArr{
    if (!_commentArr) {
        _commentArr = [NSMutableArray array];
    }
    return _commentArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = self.titleStr;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 设置刷新图片
    UIImage *images = [UIImage imageNamed:@"mj_footer"];
    NSArray *refreshingImages = @[images];
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多内容了" forState:MJRefreshStateRefreshing];
    footer.stateLabel.font = [UIFont systemFontOfSize:12.0f];
    footer.stateLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1.0f];
    
    [footer setAutomaticallyRefresh:NO];
    self.scrollview.mj_footer = footer;
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
}
-(void)loadMoreData{
    
    page++;
    
    NSMutableDictionary * dic = [NSMutableDictionary  dictionary];
        dic[@"page"] = @(page);
        dic[@"id"] = self.newsId;
    NSString *str;
    
    if ([self.titleType isEqualToString:@"PPP资讯"]) {
        
        str = @"getPppNewscommentList_app_ppp.im";
        
    }else{
        str = @"getPppSuccesscommentList_app_ppp.im";
    }
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,str];
    [LSHttpTool sendHttpData:strURl params:dic success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            if (page == 1) {
                self.commentArr = nil;
                self.commentArr = dicInfo[@"data"];
                [self.tableview reloadData];
                
            }else{
                NSArray *arr = dicInfo[@"data"];
                NSMutableArray * mtArr = [NSMutableArray array];
                for (NSDictionary * dict in self.commentArr) {
                    [mtArr addObject:dict];
                }
                for (NSDictionary * dict in arr) {
                    [mtArr addObject:dict];
                }
                self.commentArr = nil;
                self.commentArr = mtArr;
                [self.tableview reloadData];
            }
            
            [self.scrollview.mj_footer endRefreshing];
            
        }else{
            
            [self.scrollview.mj_footer endRefreshing];
        }
        
    } failure:^(NSError *error) {

        [self showSingleIconBubble:@"网络连接错误"];
        [self.scrollview.mj_footer endRefreshing];
    }];
    
}
#pragma mark - webview
-(void)setUpWebView{

    self.webView = [[UIWebView alloc] init];
    self.webView.size = [UIScreen mainScreen].bounds.size;
    self.webView.x = 0;
    self.webView.y = 0;
    self.webView.width = screenW;
    self.webView.scrollView.bounces = NO;
    self.webView.scrollView.showsHorizontalScrollIndicator = NO;
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    self.webView.delegate = self;
    self.webView.hidden = YES;
    self.webView.scrollView.contentInset = UIEdgeInsetsMake(-50, 0, 0, 0);
    [self.scrollview addSubview:self.webView];
    NSURL *url = [NSURL URLWithString:self.webUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    self.webView.scalesPageToFit = YES;
    [self.webView loadRequest:urlRequest];
    

}

-(void)webViewDidFinishLoad:(UIWebView
                             
                             *)webView{
    
    CGFloat
    
    webViewHeight=
    
    [[webView
      
      stringByEvaluatingJavaScriptFromString:
      
      @"document.body.offsetHeight"]floatValue];
    
    
    
    CGRect
    
    newFrame
    =
    webView.frame;
    
    
    
    newFrame.size.height
    
    =
    webViewHeight;
    
    
    
    webView.frame
    
    =
    newFrame;
    
    self.webView.height = newFrame.size.height + 50;
    self.webView.userInteractionEnabled = NO;
    self.scrollview.contentSize = CGSizeMake(0, self.webView.height +50);
    
    [self setUpTableView];
    [self.tableview reloadData];
    //处理“下载app的广告”
    NSString *downloadHeaderJSStr = @"document.getElementById(\"top-app-layer\").style.visibility=\"hidden\"";
    [webView stringByEvaluatingJavaScriptFromString:downloadHeaderJSStr];
    [self performSelector:@selector(btnDismiss) withObject:nil afterDelay:0.4f];
    
}

- (void)btnDismiss{
    self.webView.hidden = NO;
}
#pragma mark - tableview
-(void)setUpTableView{
    self.tableview = [[UITableView alloc] init];
    self.tableview.width = screenW;
    self.tableview.height = 130;
    self.tableview.x = 0;
    self.tableview.y = self.webView.height;
    self.tableview.scrollEnabled = NO;
    self.tableview.showsHorizontalScrollIndicator = NO;
    self.tableview.showsVerticalScrollIndicator = NO;
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    [self.scrollview addSubview:self.tableview];

    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.commentArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // 注册
    static NSString *pinlun = @"pinlunCell";
    UINib * nib = [UINib nibWithNibName:@"PinLunCell" bundle:nil];
    [self.tableview registerNib:nib forCellReuseIdentifier:pinlun];
    
    PinLunCell * cell = [self.tableview dequeueReusableCellWithIdentifier:pinlun];
    
    NSDictionary *dict = self.commentArr[indexPath.row];
    //职位 个人才有
    if ([dict[@"userType"] integerValue] == 1) {
        if ([dict[@"posiTion"] isEqualToString:@"null"] || dict[@"posiTion"] == nil) {
            cell.posiTion.text = @"";
        }else{
            cell.posiTion.text = dict[@"posiTion"];
        }
    }else{
        cell.posiTion.text = @"";
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    [cell.headPhotoImageView sd_setImageWithURL:dict[@"headPhoto"] placeholderImage:[UIImage imageNamed:@"20100403114758394_4147"]];
    
    if ([dict[@"commentUsername"] isEqualToString:@"null"] || [dict[@"commentUsername"] isEqualToString:@""]) {
        cell.userName.text = dict[@"commentAccount"];
    }else{
        cell.userName.text = dict[@"commentUsername"];
    }
    //  //判断上级
    cell.companyUserName.text = [UsedTool userType:dict[@"userType"] companyName:dict[@"companyName"] userAddress:dict[@"userAddress"]];
    CGSize sizeUserName = [cell.userName sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    CGSize sizePosition = [cell.posiTion sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    //名字长度控制
    if (sizePosition.width == 0) {
        if (sizeUserName.width > 170.0f) {
            cell.userNameConstraint.constant = 170.0f;
        }else{
            cell.userNameConstraint.constant = sizeUserName.width;
        }
    }else{
        if ((sizeUserName.width + sizePosition.width) <= 170.0f) {
            cell.userNameConstraint.constant = sizeUserName.width;
            cell.posiTionConstraint.constant = sizePosition.width;
        }else{
            
            if (sizeUserName.width >110.0f) {
                cell.userNameConstraint.constant = 110.0f;
            }else{
                cell.userNameConstraint.constant = sizeUserName.width;
            }
            if (sizePosition.width > 60.0f) {
                cell.posiTionConstraint.constant = 60.0f;
            }else{
                cell.posiTionConstraint.constant = sizePosition.width;
            }
        }
    }
    
    
    
    NSDate *date = [CustomExcetion dateFromString:dict[@"createTime"]];
    
    cell.timeLabel.text = [CustomExcetion prettyDateWithReference:date];
    
    
    
    
    cell.commentContent.text = dict[@"content"];
//    
//    if ([dict[@"authState"] integerValue]==2) {
//        
//        cell.authStateImageView.image = [UIImage imageNamed:@"yirenzheng"];
//    }else{
//        
//        cell.authStateImageView.image = [UIImage imageNamed:@"weirenzheng"];
//    }
    //认证
    cell.isAuthState.hidden = [UsedTool authStateImageViewHidden:dict[@"authState"]];
    //会员图标
    cell.authStateImageView.image = [UsedTool setVipimage:dict[@"vipLevel"]];
//    static NSString * projectcell = @"projectCell";
//    
//    // 注册
//    UINib * nib = [UINib nibWithNibName:@"projectCell" bundle:nil];
//    [self.tableview registerNib:nib forCellReuseIdentifier:projectcell];
//
//    projectCell * cell = [self.tableview dequeueReusableCellWithIdentifier:projectcell];
//    if (!cell) {
//        cell = [[projectCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:projectcell];
//    }
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.accessoryType = UITableViewCellAccessoryNone;
//    
//    [cell.headPhoto sd_setImageWithURL:[NSURL URLWithString:self.commentArr[indexPath.row][@"headPhoto"]] placeholderImage:[UIImage imageNamed:@"20100403114758394_4147"]];
//    cell.headPhoto.layer.masksToBounds = YES;
//    cell.headPhoto.layer.cornerRadius = 20.0f;
//    cell.commentUsername.textColor = [UIColor colorWithRed:23.0/255.0 green:176.0/255.0 blue:217.0/255.0 alpha:1];
//    
//    if ([self.commentArr[indexPath.row][@"commentUsername"] isEqualToString:@"null"] || [self.commentArr[indexPath.row][@"commentUsername"] isEqualToString:@""]) {
//        cell.commentUsername.text = self.commentArr[indexPath.row][@"commentAccount"];
//    }else{
//        cell.commentUsername.text = self.commentArr[indexPath.row][@"commentUsername"];
//    }
//    
//    NSDate *date = [CustomExcetion dateFromString:self.commentArr[indexPath.row][@"createTime"]];
//    cell.createTime.text = [CustomExcetion prettyDateWithReference:date];
//    
//    cell.commentLabel.text = self.commentArr[indexPath.row][@"content"];
//     [cell.commentLabel setNumberOfLines:0];
//    
//    if ([self.commentArr[indexPath.row][@"userType"] isEqualToString:@"3"]) {
//        cell.posiTion.text = @"";
//        
//        if ([self.commentArr[indexPath.row][@"goveUserName"] isEqualToString:@"null"]) {
//            cell.companyUserName.text = @"";
//        }else{
//            cell.companyUserName.text = self.commentArr[indexPath.row][@"goveUserName"];
//        }
//    }else if ([self.commentArr[indexPath.row][@"userType"] isEqualToString:@"2"]){
//        
//        if ([self.commentArr[indexPath.row][@"goveUserName"] isEqualToString:@"null"] && [self.commentArr[indexPath.row][@"companyUserName"] isEqualToString:@"null"]) {
//            
//            cell.companyUserName.text = @"";
//            
//        }else if ([self.commentArr[indexPath.row][@"goveUserName"] isEqualToString:@"null"]){
//            
//            cell.companyUserName.text = self.commentArr[indexPath.row][@"companyUserName"];
//            
//        }else if ([self.commentArr[indexPath.row][@"companyUserName"] isEqualToString:@"null"]){
//            
//            cell.companyUserName.text = self.commentArr[indexPath.row][@"goveUserName"];
//            
//        }
//        
//    }

    return cell;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    PinLunCell *cell = [self tableView:self.tableview cellForRowAtIndexPath:indexPath];
    
    //设置cell自适应高度
    UILabel *descLabel = [[UILabel alloc]init];
    
    descLabel.text = self.commentArr[indexPath.row][@"content"];
    descLabel.numberOfLines = 0;
    descLabel.font = [UIFont systemFontOfSize:14];
    CGSize constraint = CGSizeMake(screenW-16, 2000.0f);
    CGSize size = [descLabel.text sizeWithFont:descLabel.font constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
    
    
    
    
    self.tableview.height = self.tableview.contentSize.height + 10;
    self.scrollview.contentSize = CGSizeMake(0, self.webView.height + self.tableview.height);
    
    return cell.frame.size.height + size.height-16;
    
//    projectCell *cell = [self tableView:self.tableview cellForRowAtIndexPath:indexPath];
////    [cell.commentLabel setNumberOfLines:0];
//    //设置字体
//    UIFont *font = [UIFont fontWithName:@"Arial" size:12];
//    cell.commentLabel.font = font;
//    
//    CGSize constraint = CGSizeMake(250, 20000.0f);
//    
//    CGSize size = [cell.commentLabel.text sizeWithFont:font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
//    
//    [cell.commentLabel setFrame:CGRectMake(0, 0, size.width, size.height)];
//    
//    //设置cell自适应高度
//    CGRect cellFrame = [cell frame];
//    cellFrame.origin = CGPointMake(0, 0);
//    CGFloat totalHeight = cellFrame.size.height+cell.commentLabel.height;
//    cellFrame.size.height = totalHeight;
//    [cell setFrame:cellFrame];
//    
//    self.tableview.height = self.tableview.contentSize.height + 10;
//    
//    self.scrollview.contentSize = CGSizeMake(0, self.webView.height + self.tableview.height);
//    
//    return cell.frame.size.height + 20;
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenW, 22)];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 4, 22)];
    label.backgroundColor = [UIColor colorWithRed:67.0/255.0 green:177.0/255.0 blue:241.0/255.0 alpha:1];
    [view addSubview:label];
    UILabel * nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 0, 50, 22)];
    nameLabel.font = [UIFont systemFontOfSize:14];
    nameLabel.text = @"评论";
    [view addSubview:nameLabel];
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 22;
}
#pragma mark - 底部按钮
// 点赞
- (IBAction)zanBtn:(UIButton *)sender {
    
    if (allConstMemberid) {
        
        self.zanBtn.selected = !self.zanBtn.selected;
        
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        dic[@"resId"] = self.newsId;
        dic[@"userId"] = allConstMemberid;
        dic[@"token"] = allConstMemberToken;
        
        
        if (self.zanBtn.selected == NO) {
            
            dic[@"type"] = @"2";
            
        }else if (self.zanBtn.selected == YES){
            
            dic[@"type"] = @"1";
            
        }
        
        NSString *str;
        
        if ([self.titleType isEqualToString:@"PPP资讯"]) {
            
            str = @"zanPppNews_app_ppp.im.lensum";
            
        }else{
            str = @"zanPppSuccess_app_ppp.im.lensum";
        }
        
        [LSHttpTool sendHttpData:str params:dic success:^(id responseObject) {
            
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];

            
        } failure:^(NSError *error) {

            [self showSingleIconBubble:@"网络连接错误"];
            
        }];
        
    }else{
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
    
    }
    
    
}

// 关注
- (IBAction)guanZhuBtn:(UIButton *)sender {
    
    if (allConstMemberid) {
        self.guanZhuBtn.selected = !self.guanZhuBtn.selected;
        
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        dic[@"resId"] = self.newsId;
        dic[@"userId"] = allConstMemberid;
        dic[@"token"] = allConstMemberToken;
        
        
        if (self.guanZhuBtn.selected == NO) {
            
            dic[@"type"] = @"2";
            
        }else if (self.guanZhuBtn.selected == YES){
            
            dic[@"type"] = @"1";
            
        }
        
        NSString *str;
        
        if ([self.titleType isEqualToString:@"PPP资讯"]) {
            
            str = @"focusPppNews_app_ppp.im.lensum";
            
        }else{
            str = @"focusPppSuccess_app_ppp.im.lensum";
        }
        [LSHttpTool sendHttpData:str params:dic success:^(id responseObject) {
            
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
            
            
        } failure:^(NSError *error) {

            [self showSingleIconBubble:@"网络连接错误"];
            
        }];

    }else{
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
    
    }
    
}

// 分享
- (IBAction)fenXiangBtn:(UIButton *)sender {
    
    [ShareMsg shareMsgBOOLType:NO titleStr:self.dataDict[@"type"] contentStr:self.dataDict[@"title"] urlStr:self.dataDict[@"content"] imageAry:nil];
        
}
// 发表评论
- (IBAction)clickCommetBtn {
}

- (IBAction)sendComment:(UITextField *)sender {
    
    if (allConstMemberid) {
        if (self.textfiled.text.length != 0) {
            
            // 请求数据
            NSMutableDictionary * dic = [NSMutableDictionary dictionary];
            dic[@"resId"] = self.newsId;
            dic[@"userId"] = allConstMemberid;
            dic[@"token"] = allConstMemberToken;
            dic[@"content"] = self.textfiled.text;
            
            NSString *str;
            
            if ([self.titleType isEqualToString:@"PPP资讯"]) {
                
                str = @"commentPppNews_app_ppp.im.lensum";
                
            }else{
                str = @"commentPppsuccess_app_ppp.im.lensum";
            }
            [LSHttpTool sendHttpData:str params:dic success:^(id responseObject) {
                
                self.textfiled.text = @"";
                [self sendRequest];
                //            [self.scrollview.mj_footer beginRefreshing];

                [self showRightWithTitle:@"评论成功!" autoCloseTime:2];
                
            } failure:^(NSError *error) {

                [self showSingleIconBubble:@"网络连接错误"];
                
            }];
        }else{

            [self showSingleIconBubble:@"内容不能为空"];
        }
    }else{
    
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
    
    }
    
}

-(void)sendRequest{
    self.tableview = nil;
    self.webView = nil;
    // 请求数据
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    dic[@"id"] = self.newsId;
    dic[@"userId"] = allConstMemberid;
    
    NSString *str;
    
    if ([self.titleType isEqualToString:@"PPP资讯"]) {
        
        str = @"getPppNewsDetail_app_ppp.im";
        
    }else{
        str = @"getPppSuccessDetail_app_ppp.im";
    }
    [LSHttpTool sendHttpData:str params:dic success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        self.dataDict = dicInfo[@"data"];
        self.commentArr = self.dataDict[@"commentsList"];
        if ([self.dataDict[@"isFocus"]integerValue] == 0) {
            self.guanZhuBtn.selected = NO;
        }else{
            self.guanZhuBtn.selected = YES;
        }
        
        if ([self.dataDict[@"isZan"]integerValue] == 0) {
            self.zanBtn.selected = NO;
        }else{
            self.zanBtn.selected = YES;
        }
        [self setUpWebView];
        
    } failure:^(NSError *error) {

        [self showSingleIconBubble:@"网络连接错误"];

    }];

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        //登录
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [self presentViewController:loginNAV animated:YES completion:nil];
    }
    
    
}
@end
